#!/bin/sh

# Copied.
##################################################################################
#                                                                                #
# universalJavaApplicationStub                                                   #
#                                                                                #
#                                                                                #
# A shellscript JavaApplicationStub for Java Apps on Mac OS X                    #
# that works with both Apple's and Oracle's plist format.                        #
#                                                                                #
# Inspired by Ian Roberts stackoverflow answer                                   #
# at http://stackoverflow.com/a/17546508/1128689                                 #
#                                                                                #
#                                                                                #
# @author    Tobias Fischer                                                      #
# @url       https://github.com/tofi86/universalJavaApplicationStub              #
# @date      2014-03-16                                                          #
# @version   0.3                                                                 #
#                                                                                #
#                                                                                #
##################################################################################
#                                                                                #
#                                                                                #
# The MIT License (MIT)                                                          #
#                                                                                #
# Copyright (c) 2014 Tobias Fischer                                              #
#                                                                                #
# Permission is hereby granted, free of charge, to any person obtaining a copy   #
# of this software and associated documentation files (the "Software"), to deal  # 
# in the Software without restriction, including without limitation the rights   #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell      #
# copies of the Software, and to permit persons to whom the Software is          #
# furnished to do so, subject to the following conditions:                       #
#                                                                                #
# The above copyright notice and this permission notice shall be included in all #
# copies or substantial portions of the Software.                                #
#                                                                                #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR     #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,       #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE    #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER         #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  #
# SOFTWARE.                                                                      #
#                                                                                #
##################################################################################




#
# resolve symlinks
#####################

PRG=$0

while [ -h "$PRG" ]; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '^.*-> \(.*\)$' 2>/dev/null`
    if expr "$link" : '^/' 2> /dev/null >/dev/null; then
        PRG="$link"
    else
        PRG="`dirname "$PRG"`/$link"
    fi
done

PROGDIR=`dirname "$PRG"`




#
# read Info.plist and extract JVM options
############################################

# set Apple's Java folder
AppleJavaFolder="$PROGDIR/../Resources/Java/"

# set Oracle's Java folder
OracleJavaFolder="$PROGDIR/../Java/"

# set path to Info.plist in bundle
InfoPlistFile="$PROGDIR/../Info.plist"


# read the program name from CFBundleName
CFBundleName=`/usr/libexec/PlistBuddy -c "print :CFBundleName" ${InfoPlistFile}`

# read the icon file name
CFBundleIconFile=`/usr/libexec/PlistBuddy -c "print :CFBundleIconFile" ${InfoPlistFile}`


# read Info.plist in Apple style
if [ -d "${AppleJavaFolder}" ]; then

	# set working directory
	JavaFolder="${AppleJavaFolder}"
	ResourcesFolder=".."

	# read the MainClass name
	JVMMainClass=`/usr/libexec/PlistBuddy -c "print :Java:MainClass" ${InfoPlistFile} 2> /dev/null`

	# read the JVM Options
	JVMOptions=`/usr/libexec/PlistBuddy -c "print :Java:Properties" ${InfoPlistFile} 2> /dev/null | grep " =" | sed 's/^ */-D/g' | tr '\n' ' ' | sed 's/  */ /g' | sed 's/ = /=/g' | xargs`

	# read the JVM Default Options
	JVMDefaultOptions=`/usr/libexec/PlistBuddy -c "print :Java:VMOptions" ${InfoPlistFile} 2> /dev/null | xargs`

	# read the JVM Arguments
	JVMArguments=`/usr/libexec/PlistBuddy -c "print :Java:Arguments" ${InfoPlistFile} 2> /dev/null | xargs`


# read Info.plist in Oracle style
elif [ -d "${OracleJavaFolder}" ]; then

	# set working directory
	JavaFolder="${OracleJavaFolder}"
	ResourcesFolder="../Resources"

	# read the MainClass name
	JVMMainClass=`/usr/libexec/PlistBuddy -c "print :JVMMainClassName" ${InfoPlistFile} 2> /dev/null`

	# read the JVM Options
	JVMOptions=`/usr/libexec/PlistBuddy -c "print :JVMOptions" ${InfoPlistFile} 2> /dev/null | grep " -" | tr '\n' ' ' | sed 's/  */ /g' | xargs`

	# read the JVM Default Options
	JVMDefaultOptions=`/usr/libexec/PlistBuddy -c "print :JVMDefaultOptions" ${InfoPlistFile} 2> /dev/null | grep -o "\-.*" | tr '\n' ' ' | xargs`

	# read the JVM Arguments
	JVMArguments=`/usr/libexec/PlistBuddy -c "print :JVMArguments" ${InfoPlistFile} 2> /dev/null | tr '\n' ' ' | sed -E 's/Array \{ *(.*) *\}/\1/g' | sed 's/  */ /g' | xargs`

fi




#
# find installed Java versions
#################################

# first check system variable "$JAVA_HOME"
if [ -n "$JAVA_HOME" ]; then
	JAVACMD="$JAVA_HOME/bin/java"

# otherwise check "/usr/libexec/java_home" symlinks
elif [ -x /usr/libexec/java_home ]; then
	JAVACMD="`/usr/libexec/java_home`/bin/java"

# otherwise check Java standard symlink (old Apple Java)
elif test -h /Library/Java/Home; then
	JAVACMD="/Library/Java/Home/bin/java"

# fallback: public JRE plugin (Oracle Java)
else
	JAVACMD="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java"
fi

# fallback fallback: /usr/bin/java
# but this would prompt to install deprecated Apple Java 6




#
# execute JAVA commandline and do some pre-checks
####################################################

# display error message if MainClassName is empty
if [ ${JVMMainClass} == "" ]; then
	# display error message with applescript
	osascript -e "tell application \"System Events\" to display dialog \"ERROR launching ${CFBundleName}!\n\nNo MainClassName specified!\nJava application cannot be started!\" with title \"${CFBundleName}\" buttons {\" OK \"} default button 1 with icon path to resource \"${CFBundleIconFile}\" in bundle (path to me)"
	# exit with error
	exit 1


# check whether $JAVACMD is executable
elif [ -x "$JAVACMD" ]; then

	# enable drag&drop to the dock icon
	export CFProcessPath="$0"

	cd "$JavaFolder"

	# execute Java and set
	#	- classpath
	#	- dock icon
	#	- application name
	#	- JVM options
	#	- JVM default options
	#	- main class
	#	- JVM arguments
	exec "$JAVACMD" \
			-cp "./*" \
			-Xdock:icon="$ResourcesFolder/${CFBundleIconFile}" \
			-Xdock:name="${CFBundleName}" \
			${JVMOptions:+$JVMOptions }\
			${JVMDefaultOptions:+$JVMDefaultOptions }\
			"${JVMMainClass}"\
			${JVMArguments:+$JVMArguments}


else

	# display error message with applescript
	osascript -e "tell application \"System Events\" to display dialog \"ERROR launching ${CFBundleName}!\n\nYou need to have JAVA installed on your Mac!\nVisit http://java.com for more information...\" with title \"${CFBundleName}\" buttons {\" OK \"} default button 1 with icon path to resource \"${CFBundleIconFile}\" in bundle (path to me)"

	# and open java.com
	open http://java.com

	# exit with error
	exit 1
fi
